package cn.karent.common;

import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.SmartValidator;
import org.springframework.validation.beanvalidation.CustomValidatorBean;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wanshengdao
 * @date 2025/3/20
 */
public class ValidationUtils {

    private static final SmartValidator validator;

    static {
        CustomValidatorBean bean = new CustomValidatorBean();
        bean.afterPropertiesSet();
        validator = bean;
    }

    /**
     * 校验
     *
     * @param obj 待校验的对象
     */
    public static void valid(Object obj) {
        if (validator.supports(obj.getClass())) {
            BeanPropertyBindingResult bindError = new BeanPropertyBindingResult(obj, obj.getClass().getSimpleName());
            validator.validate(obj, bindError);
            if (bindError.hasErrors()) {
                List<FieldError> fieldErrors = bindError.getFieldErrors();
                String msg = fieldErrors.stream().map(item -> item.getField() + ":" + item.getDefaultMessage()).collect(Collectors.joining(";"));
                throw new IllegalArgumentException(String.format("参数校验错误: %s", msg));
            }
        }
    }

}
